<?php
namespace App\Lib;

//腾讯 实名认证
use Illuminate\Support\Facades\Redis;

class faceTencent
{

    public $apiKey;
    public $apiSecret;
//    private $apiKey = 'TIDAUbbo';
//    private $apiSecret = 'lQnpslgwum7dwPgar5CZo3SJNnZn7MtYV6YxSNmgD79yRbjaynbNdDWMVgYnnqUI';

    private $version = '1.0.0';

    public $accessTokenKey = 'TENCENT:FACE:ACCESS_TOKEN:';
    public $signTicketKey = 'TENCENT:FACE:SIGN_TICKET:';

    public function __construct()
    {
        $this->apiKey = config("tx_face.appId");
        $this->apiSecret = config("tx_face.secret");
    }

    public function refreshAccessToken() {
        $url = 'https://kyc1.qcloud.com/api/oauth2/access_token';
        $param = [
            'appId' => $this->apiKey,
            'secret' => $this->apiSecret,
            'grant_type' => 'client_credential',
            'version' => $this->version,
        ];

        $result = curl_request($url, $param, 'urlencoded', 'GET');
        $ret_data = json_decode($result, true);
        if ($ret_data['code'] != 0){
            write_log('faceTencent', 'refreshAccessToken', $ret_data);
            return null;
        }

        $token = $ret_data['access_token'];

        // 设置缓存
        Redis::setex($this->accessTokenKey, 3600, $token);

        return $token;

    }

    public function getAccessToken() {
        $token = Redis::get($this->accessTokenKey);
        if (!empty($token)) {
            return $token;
        }
        return $this->refreshAccessToken();
    }

    public function getSignTicket() {
        $sign = Redis::get($this->signTicketKey);
        if (!empty($sign)) {
            return $sign;
        }
        return $this->refreshSignTicket();
    }

    public function refreshSignTicket() {
        $url = 'https://kyc1.qcloud.com/api/oauth2/api_ticket';
        $param = [
            'appId' => $this->apiKey,
            'access_token' => $this->getAccessToken(),
            'type' => 'SIGN',
            'version' => $this->version,
        ];

        $result = curl_request($url, $param, 'urlencoded', 'GET');
        $ret_data = json_decode($result, true);
        if ($ret_data['code'] != 0){
            write_log('faceTencent', 'refreshSignTicket', $ret_data);
            return null;
        }

        $ticket = $ret_data['tickets'][0]['value'];

        // 设置缓存
        Redis::setex($this->signTicketKey, 3600, $ticket);

        return $ticket;

    }

    public function getNonceTicket($user_id) {
        $url = 'https://kyc1.qcloud.com/api/oauth2/api_ticket';
        $param = [
            'appId' => $this->apiKey,
            'access_token' => $this->getAccessToken(),
            'type' => 'NONCE',
            'version' => $this->version,
            'user_id' => $user_id,
        ];

        $result = curl_request($url, $param, 'urlencoded', 'GET');
        $ret_data = json_decode($result, true);
//        var_dump($ret_data);
        if ($ret_data['code'] != 0){
            write_log('faceTencent', 'getNonceTicket', $ret_data);
            return null;
        }
        return $ret_data['tickets'][0]['value'];

    }

    public function getFrontSign($user_id, $nonce){
        $ticket_nonce = $this->getNonceTicket($user_id);

        $arr=array(
            $this->apiKey,
            $user_id,
            $nonce,
            $this->version,
            $ticket_nonce
        );

        // natsort($arr);

        asort($arr,SORT_STRING);
        $str =implode('',$arr);

        $sign=sha1($str);

        return $sign;
    }

    public function getBackendSign($nonce, $user_id , $orderNo = '') {
        $ticket_nonce = $this->getSignTicket();

        $arr=array(
            $this->apiKey,
            $nonce,
            $this->version,
            $ticket_nonce
        );

        if ($user_id) {
            $arr[] = $user_id;
        }

        if ($orderNo) {
            $arr[] = $orderNo;
        }

        asort($arr,SORT_STRING);
        $str =implode('',$arr);

//        natsort($arr);
//
//        $str='';
//        foreach ($arr as $v) {
//            $str.=$v;
//        }

        $sign=sha1($str);

        return $sign;
    }

    public function getFaceId($user_id, $name, $idNo, $orderNo, $nonce) {
        $backendSign = $this->getBackendSign($nonce, $user_id);

        $url = 'https://kyc1.qcloud.com/api/server/getfaceid?orderNo=' . $orderNo;
        $data = [
            'appId' => $this->apiKey,
            'orderNo' => $orderNo,
            'name' => $name,
            'idNo' => $idNo,
            'userId' => $user_id,
            'version' => $this->version,
            'sign' => $backendSign,
            'nonce' => $nonce,
        ];

        $result = curl_request($url, $data, 'json', 'POST');

        $ret_data=json_decode($result,true);

        if ($ret_data['code'] != 0) {
            write_log('faceTencent', 'getFaceId', $ret_data);
            // TODO 错误
            return $ret_data['code'];
        }

        return $ret_data['result']['faceId'];

    }

    public function verify($orderNo, $nonce) {
        $backendSign = $this->getBackendSign($nonce, '', $orderNo);

        $url = 'https://kyc1.qcloud.com/api/v2/base/queryfacerecord?orderNo=' . $orderNo;
        $data = [
            'appId' => $this->apiKey,
            'orderNo' => $orderNo,
            'version' => $this->version,
            'sign' => $backendSign,
            'nonce' => $nonce,
            'getFile' => '2',//是否需要获取人脸识别的视频和文件，值为1则返回视频和照片、值为2则返回照片、值为3则返回视频；其他则不返回
        ];

        $result = curl_request($url, $data, 'json', 'POST');

        $ret_data=json_decode($result,true);

        write_log('faceTencentVerify', 'verify', $ret_data);

        return $ret_data;

    }

    public function getOrderNo() {
        return 'TX'. date('YmdHis') .rand(100000, 999999);
    }

    /* 随机数 */
    public function random($length = 32 , $numeric = false) {
        if($numeric) {
            $hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
        } else {
            $hash = '';
            $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
            $max = strlen($chars) - 1;
            for($i = 0; $i < $length; $i++) {
                $hash .= $chars[mt_rand(0, $max)];
            }
        }
        return $hash;
    }


}
